import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;



public class DS_DB implements IDS 
{
	private String conName = "";
	
	public DS_DB( String conName )
	{
		this.conName = conName;
	}

	@Override
	public void Save(List<Person> pp) 
	{
		try 
		{
			Class.forName("org.h2.Driver");
			Connection con = DriverManager.getConnection("jdbc:h2:~/test", "sa", "");
			Statement st = con.createStatement();
			String sql = "Delete from Person;";
			st.executeUpdate(sql);
			for( Person p : pp)
			{
				sql = "INSERT INTO Person VALUES (" + p.toSqlString() + ");";
				st.execute(sql);
			}
			st.close();
			con.close();
		}
		catch (ClassNotFoundException e) 
		{
			e.printStackTrace();
		}
		catch (SQLException e) 
		{
			e.printStackTrace();
		}
		
	}

	@Override
	public List<Person> Load() 
	{		
		List<Person> pp = new ArrayList<Person>();
		try 
		{
			Class.forName("org.h2.Driver");
			Connection con = DriverManager.getConnection("jdbc:h2:~/test", "sa", "");
			Statement st = con.createStatement();		
			ResultSet resultSet = st.executeQuery("SELECT * FROM Person;");
			while (resultSet.next()) 
			{
				Person p = new Person( resultSet.getInt(1),	resultSet.getString(2), resultSet.getString(3),	resultSet.getInt(4) );
				pp.add( p );
				System.out.println(p.toString());
			}
			resultSet.close();
			st.close();
			con.close();
		}
		catch (ClassNotFoundException e) 
		{
			e.printStackTrace();
		}
		catch (SQLException e) 
		{
			e.printStackTrace();
		}
		
		return pp;
	}

}
